<template>
  <div class="goodsStandards">
    <div id="form-wrapper">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规格名称"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="ruleForm.price" placeholder="请输入价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="加盟商价格" prop="m_price">
          <el-input v-model="ruleForm.m_price" placeholder="请输入加盟商价格"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="ruleForm.stock" type="number" placeholder="请输入库存"></el-input>
        </el-form-item>
        <el-form-item label=" 规格图片 (比例 1:1)" prop="titleFileList">
          <el-upload
            accept=".png, .jpeg, .jpg"
            :action="$api + '/v1/upload/image'"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :on-success="fileSuccess"
            :auto-upload="true"
            :file-list="ruleForm.titleFileList"
            :limit="titleFileMaxCount"
            :class="{'hide': fileToLarge}"
            name="name"
            :data="{'token': token}"
          >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="close">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
   <el-dialog :visible.sync="dialogPic" :modal-append-to-body="false" :modal="false" custom-class="isX">
      <img width="100%" :src="dialogImg" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    name: 'GoodsStandards',
    props: {
      id: String,
      isEdit: Boolean
    },
    data() {
      return {
        token: localStorage.getItem('token'),
        ruleForm: {
          name: '',
          price: '',
          m_price: '',
          stock: '',
          titleFileList: []
        },
        rules: {
          name: [
            { required: true, message: '请输入类别名称', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^([1-9]\d{0,8}|0)(\.\d{1,2})?$/).test(value)
                if(!boolean) {
                  return callback(new Error('请正确输入商品价格'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
          m_price: [
            { required: true, message: '请输入加盟商价格', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^([1-9]\d{0,8}|0)(\.\d{1,2})?$/).test(value)
                if(!boolean) {
                  return callback(new Error('请正确输入加盟商价格'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
          stock: [
            { required: true, message: '请输入商品库存', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^[1-9][0-9]*$/).test(value)
                if (!boolean) {
                    return callback(new Error('请输入正整数'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
          titleFileList: [
            { type: 'array', required: true, message: '请上传规格图片' }
          ]
        },
        titleFileMaxCount: 1,
        dialogImg: '',
        dialogPic: false,
        disabled: false,
        dialogImageUrl: '',
        dialogVisible: false
      }
    },
    computed: {
      fileToLarge() {
        return this.ruleForm.titleFileList.length >= this.titleFileMaxCount
      },
      fileIdArr() {
        return this.ruleForm.titleFileList.map((item) => {
          return item.id
        }).toString()
      }
    },
    methods: {
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        const isLt10M = file.size / 1024 / 1024 < 10
      
        if (!isJPG) {
          this.$message.warning('上传头像图片只能是 JPG | PNG 格式!')
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isJPG && isLt10M
      },
      // 删除图片的事件
      handleRemove(file) {
        this.ruleForm.titleFileList = this.ruleForm.titleFileList.filter((item) => {
          return file.id !== item.id
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImg = file.url;
        this.dialogPic = true;
      },
      fileSuccess(r, file) {
        file.id = file.response.data.id
        this.ruleForm.titleFileList.push({...file})
      },
      submitForm: _.throttle(function() {
        this.$refs.ruleForm.validate(async (valid) => {
          if(!valid) {
            return false
          }
          
          try{
            let { data: { code, data } } = await this.$axios({
              url: this.$api + '/v1/gauge/increase',
              method: 'POST',
              data: {
                name: this.ruleForm.name,
                price: this.ruleForm.price,
                m_price: this.ruleForm.m_price,
                stock: this.ruleForm.stock,
                pic_id: this.fileIdArr
              }
            })
            
            if(code == 0) {
               let guageData = {
                 id: data.id,
                 name: data.name,
                 m_price: data.m_price,
                 price: data.price,
                 stock: data.stock,
                 imgUrl: this.ruleForm.titleFileList[0].url
               }
               this.$emit('guageSuccess', guageData)
               this.close()
            } else {
              this.$message.warning(data.message)
            }
          }catch(e){
            this.$message({
              type: 'error',
              message: e
            })
          }
        })
      },2000,{
        trailing: false
      }),
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      close() {
        this.$emit('close')
        this.resetForm('ruleForm')
      }
    }
  }
</script>

<style lang="scss">
  #form-wrapper {
    width: 50%;
    margin: 0 auto;
  }
  .hide .el-upload--picture-card {
    display: none;
  }
  .goodsStandards {
    .isX {
      .el-icon-close:before {
        content: "\E6DB"
      }
    }
  }
  
</style>
